#! /bin/node
// @ts-check
const util = require("node:util");
const path = require("node:path");
const child_process = require("child_process");
const { writeFile, readFile } = require("node:fs/promises");
const exec = util.promisify(child_process.exec);
const meta = require("./meta.json");

/**
 * @param {TemplateStringsArray} s
 */
function green(s) {
  return `\x1b[42m${s}\x1b[0m`;
}

async function main() {
  // TODO
  const { stdout } = await exec('pwsh -c "$PROFILE"');
  const targetPs1 = stdout.trim();
  try {
    path.resolve(targetPs1);
  } catch {
    throw new Error("Could not resolve pwsh profile path: '" + targetPs1 + "'");
  }
  const profileDir = path.dirname(targetPs1);
  const here = path.resolve(__dirname, "./Boot.ps1");
  console.log(profileDir, "->", here);
  const cmd = `. (Join-Path \"${__dirname}\" \"./Boot.ps1\") # REPO_ROOT: ${__dirname }`;
  const cmdReg =
    // 匹配任意 待定仓库路径的字符串
    /\.\s\(Join-Path\s['"](?:.*)['"]\s["'].[\\\/]Boot\.ps1["']\)/i;

  // do fs
  const oldProfile = await readFile(targetPs1, "utf-8");
  // 如果更改了克隆的仓库的路径, 还需要手动重置到'$PSScriptRoot'
  await writeFile(targetPs1, oldProfile.replace(cmdReg, cmd), {
    encoding: "utf-8",
    flag: "w",
  });
  console.log(green`[DONE]`);
}

if (process.platform === "win32") {
  main();
}
